package org.cainiao.scenario.highconcurrency;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.cainiao.scenario.highconcurrency.mapper.OrderMapper;
import org.cainiao.scenario.highconcurrency.service.StockService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderConsumer {

    private final OrderMapper orderMapper;
    private final StockService stockService;

    // RocketMQ监听器配置
    @RocketMQMessageListener(
        topic = "seckill_topic",
        selectorExpression = "order_tag", // 选择tag
        consumerGroup = "seckill_order_group"
    )
    public class OrderListener implements RocketMQListener<SeckillMessage> {
        @Override
        public void onMessage(SeckillMessage message) {
            try {
                // 数据库唯一索引防重复
                orderMapper.insertOrder(message.getUserId(), message.getItemId());
                // 同步库存数据库（最终一致性）
                stockService.reduceDBStock(message.getItemId());
            } catch (DuplicateKeyException e) {
                // 幂等性处理：已存在的订单直接跳过
                log.warn("重复订单: {}", message.getOrderId());
            }
        }
    }
}
